﻿using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using OpenWaves.Web;
using OpenWaves.Reflection;

namespace OpenWaves.Testing.CodeAnalysisRules
{
    public class PagesAndControlsEmbededInResourcesShouldBeMarkedAsPublicResources : ICodeAnalysisRule
    {
        public void Run(Assembly assembly)
        {
            CheckWebResourcesMarkedAsPublicResources(assembly);
        }

        public static void CheckRequiredPublicResources(Assembly assembly, Func<string, bool> requiredVerifier)
        {
            var publicResourceNames = assembly.GetCustomAttributes<PublicAssemblyResourcesAttribute>().SelectMany(a => a.ResourceNames);

            foreach (string resourceName in assembly.GetManifestResourceNames())
            {
                bool requiresPublicAttribute = requiredVerifier(resourceName);
                if (requiresPublicAttribute)
                {
                    Assert.Contains(resourceName, publicResourceNames.ToArray(), "{0} is not exposed as a public resource.", resourceName);
                }
            }
        }

        public static void CheckWebResourcesMarkedAsPublicResources(Assembly assembly)
        {
            Func<string, bool> requiredVerifier =
                resourceName => resourceName.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase)
                                || resourceName.EndsWith(".ascx", StringComparison.InvariantCultureIgnoreCase)
                                || resourceName.EndsWith(".ashx", StringComparison.InvariantCultureIgnoreCase);

            CheckRequiredPublicResources(assembly, requiredVerifier);
        }
    }
}